package javafoundations;

import java.util.Arrays;

public class ArrayStack<T> implements Stack<T> {
    private final int DEFAULT_CAPACITY = 10;

    private int count;
    private T[] stack;

    public ArrayStack() {
        count = 0;
        stack = (T[]) (new Object[DEFAULT_CAPACITY]);

    }

    public ArrayStack(int initialCapacity){
        count = 0;
        stack = (T[])(new Object[initialCapacity]);

    }

    public int Size(){
        return count ;
    }

    public boolean isEmpty(){
        if(Size() == 0) {
            return true;
        }
        else
        {
            return false;
        }
    }

    //
    public void push (T element)
    {
        if (Size() == stack.length)
            expandCapacity();
        stack[count] = element;
        count++;

    }

    public void expandCapacity(){
        stack = Arrays.copyOf(stack, stack.length * 2);

    }

    //pop
    public T pop() throws EmptyCollection
    {
        if(isEmpty()) {
            throw new EmptyCollection("Stack");
        }
        count--;
        T result = stack[count];
        stack[count] = null;

        return result;

    }


    public T peek()throws EmptyCollection
    {
        if(isEmpty()) {
            throw new EmptyCollection("Stack");
        }
        return stack[count-1];
    }

    public String toString()
    {
        String line = "";

        for(int i = 0 ; i < count; i++)
        {
            line +=  stack[i]+"";
        }
        return line;
    }
}
